using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using SdlDotNet.Graphics.Sprites;
using SdlDotNet.Graphics;
using System.Collections;

namespace SnakeCharp.Entity
{
    public class SnakeTail : LinkedList<SnakeTailNode>
    {
        private Point startingPoint;
        private float speed;
        private int length = 4;
        private int lengthCounter = 0;


        public SnakeTail(Point headPoint, float speed)
        {
            this.startingPoint = headPoint;
            this.speed = speed;

            //Default TailNodes
            this.AddLast(new SnakeTailNode(headPoint));
            this.AddLast(new SnakeTailNode(headPoint));
            this.AddLast(new SnakeTailNode(headPoint));
        }

        public void Update(Point headPoint, float speed)
        {
            //ToDo: I guess the following code can be optimized
            //For now it is just working, almost
            foreach (SnakeTailNode node in this)
            {
                //All SnakeNode's need the new position point
                node.PositionQueue.Enqueue(headPoint);

                if (!node.IsMoving)
                {
                    if (lengthCounter >= length)
                    {
                        node.IsMoving = true;
                        lengthCounter = 0;
                    }
                }

                if (node.IsMoving)
                    node.Update();
            }
            if (lengthCounter >= length)
                lengthCounter = 0;
            else
                lengthCounter++;
        }

        public void Render(float interpolation, Surface destinationSurface)
        {
            foreach (SnakeTailNode node in this)
            {
                //ToDo: Put in some interpolation code here
                destinationSurface.Blit(node);
            }
        }

        public void AddTailNode()
        {
            SnakeTailNode node = new SnakeTailNode(this.Last.Value.Center);
            node.PositionQueue = this.Last.Value.CopyOfQueue();
            this.AddLast(node);
            lengthCounter = 0;
        }

        public void RemoveTailNode()
        {
            if(this.Last != null)
                this.RemoveLast();
        }
    }
}
